package com.atguigu.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.*;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/2/9 9:16
 */
public class DwdLogApp extends BaseAppV1 {
    
    private final String START = "start";
    private final String PAGE = "page";
    private final String DISPLAY = "display";
    
    public static void main(String[] args) {
        new DwdLogApp().init(2001, 1, "DwdLogApp", "DwdLogApp", Constant.TOPIC_ODS_LOG);
    }
    
    @Override
    public void run(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 实现具体的业务
        // 1. 区别新老客户
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(stream);
        // 2. 分流: 页面  曝光 启动   侧输出流
        Map<String, DataStream<JSONObject>> threeStreams = splitStream(validatedStream);
        // 3. 不同流的数据写入到不同的topic中
        write2Kafka(threeStreams);
    }
    
    private void write2Kafka(Map<String, DataStream<JSONObject>> threeStreams) {
        threeStreams
            .get(START)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        
        threeStreams
            .get(DISPLAY)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        
        threeStreams
            .get(PAGE)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
    }
    
    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {};
        // 侧输出流, 需要使用上下文, process中有
        /*
        分三个流:
        启动  主流
        页面  测输出流
        曝光  测输出流
         */
        SingleOutputStreamOperator<JSONObject> startStream = validatedStream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject value,
                                       Context ctx,
                                       Collector<JSONObject> out) throws Exception {
                // 判断是否为启动日志
                if (value.containsKey("start")) {
                    // 是启动日志
                    out.collect(value);
                    
                } else {
                    // 是否为页面日志
                    if (value.containsKey("page")) {
                        ctx.output(pageTag, value);
                    }
                    
                    // 是否为曝光日志
                    if (value.containsKey("displays")) {
                        /*
                        {
                            "display_type":"query",
                            "item":"1",
                            "item_type":"sku_id",
                            "pos_id":2,
                            "order":2
                        }
                         */
                        JSONArray displays = value.getJSONArray("displays");
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            // 把一些其他的数据放入到display这个map中
                            display.putAll(value.getJSONObject("common"));
                            display.putAll(value.getJSONObject("page"));
                            display.put("ts", value.getLong("ts"));
                            ctx.output(displayTag, display);
                        }
                    }
                    
                }
                
            }
        });
        
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        
        Map<String, DataStream<JSONObject>> map = new HashMap<>();
        map.put(START, startStream);
        map.put(PAGE, pageStream);
        map.put(DISPLAY, displayStream);
        return map;
        
    }
    
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(DataStreamSource<String> stream) {
        /*
        验证新老用户:
            第一条访问记录  is_new 是 1
            其他的所有访问记录都应该是 0
            
            解决乱序: 使用事件时间+窗口
            
            {
              "common": {
                "ar": "310000",
                "ba": "Xiaomi",
                "ch": "xiaomi",
                "is_new": "0",
                "md": "Xiaomi 10 Pro ",
                "mid": "mid_24",
                "os": "Android 11.0",
                "uid": "48",
                "vc": "v2.1.134"
              },
              "page": {
                "during_time": 16336,
                "item": "2,6,7",
                "item_type": "sku_ids",
                "last_page_id": "cart",
                "page_id": "trade"
              },
              "ts": 1644370300000
            }
        
         */
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Boolean> firstWindowState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstWindowState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Boolean>("fistWindowState", Boolean.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    
                    /*
                    第一个窗口中的时间戳最小的那个是 1 其他的都是0
                    其他的窗口中所有都是 0
                     */
                    if (firstWindowState.value() == null) {
                        // 第一个窗口
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        /*Collections.min(list, new Comparator<JSONObject>() {
                            @Override
                            public int compare(JSONObject o1, JSONObject o2) {
                                return o1.getLong("ts").compareTo(o2.getLong("ts"));
                            }
                            
                        });*/
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (JSONObject obj : list) {
                            if (obj == min) {
                                obj.getJSONObject("common").put("is_new", 1);
                            } else {
                                obj.getJSONObject("common").put("is_new", 0);
                            }
                            out.collect(obj);
                        }
                        
                        // 更新状态
                        firstWindowState.update(true);
                    } else {
                        // 不是第一个窗口
                        for (JSONObject obj : elements) {
                            obj.getJSONObject("common").put("is_new", 0);
                            
                            out.collect(obj);
                        }
                        
                    }
                }
            });
        
    }
}
